package com.winning.shiro.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;

/**
 * @author Lenovo
 * @title 多Realm--第二Realm 使用SHA1密码进行加密
 * @project shiro-web
 * @package com.winning.shiro.realm
 * @date: 2019-01-18 10:11
 */
public class SecondShiroRealm extends AuthenticatingRealm {

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println(" [ Second Realm ] doGetAuthenticationInfo ");
        // 1. 获取UsernamePasswordToken
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        // 2.获取用户名
        String username = (String) upToken.getPrincipal();
        // 3.调用数据库方法，从数据库中获取对应的数据库数据
        System.out.println("从数据库中获取username："+username+"所对应的用户信息");
        // 4.若用户不存在，则可以抛出UnknownAccountException
        if("unknown".equals(username)){
            throw new UnknownAccountException("用户不存在");
        }
        // 5.根据用户信息的情况，决定是否需要抛出其他AuthenticationException
        if("xx".equals(username)){
            throw new LockedAccountException("用户被锁定异常");
        }
        // 6.根据用户情况，来构建AuthenticationInfo 对象并返回
        // 通常使用的是：SimpleAuthenticationInfo
        // 参数为：
        // 1）principal 用户名，认证的实体名称
        Object principal = username;
        // 2）credentials: 密码，认证的凭证 数据库获取的密码 会与token中存放的密码进行比对
        Object credentials = "";
        if("admin".equals(username)){
            credentials = "ce2f6417c7e1d32c1d81a797ee0b499f87c5de06";
        }else if ("user".equals(username)){
            credentials = "073d4c3ae812935f23cb3f2a71943f49e082a718";
        }
        // 3）realmName:当前的realm的名称，使用getName方法即可
        String realmName = getName();
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal,credentials,realmName);
        // 4）salt 盐值
        ByteSource credentialsSalt = ByteSource.Util.bytes(username);
        info = new SimpleAuthenticationInfo(principal+"@test",credentials,credentialsSalt,realmName);
        return info;
    }

    public static void main(String[] args){
        /* 计算MD5加密1024次密码值 */
        String hashAlgorithmName = "SHA1";
        Object credentials = "123456";
        Object salt =  ByteSource.Util.bytes("admin");
        int hashIterations = 1024;
        Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
        System.out.println(result);
    }

}
